package com.wry.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * <h1> 客户端TimeClientHandler <h1>
 *
 * @author wry
 * @since 2023/4/18 14:54
 */
public class TimeClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            ByteBuf byteBuf = (ByteBuf) msg;
            final int length = byteBuf.readableBytes();
            byte[] bytes = new byte[1024];
            byteBuf.readBytes(bytes, 0, length);
            System.out.println("current time: " + new String(bytes, 0, length));
            ctx.close();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
